﻿using AutoMapper;
using B.S.PrimaryProject.Domain;
using B.S.PrimaryProject.ErrorCode;
using B.S.PrimaryProject.Infrastructure.Interfaces;
using B.S.PrimaryProject.API.Applications.Commands.Users;
using B.S.PrimaryProject.API.Dtos;
using MD5Hash;
using MediatR;

namespace B.S.Meeting.ReadAPI.Applications.CommandHandlers.Users
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<UserDto>>
    {
        IBaseRepository<User> uRep;
        IMapper mapper;
        ILogger<LoginCommandHandler> logger;

        public LoginCommandHandler(IBaseRepository<User> uRep, IMapper mapper, ILogger<LoginCommandHandler> logger)
        {
            this.uRep = uRep;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<APIResult<UserDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var user=uRep.GetAll().FirstOrDefault(x=>x.UserName==request.UserName);
                if (user == null)
                {
                    return new APIResult<UserDto>
                    {
                        Code=StatusEnumCode.Fail,
                        Message="用户名不存在",
                        Data=null
                    };
                }
                if (user.UserPwd == request.UserPwd.GetMD5()) 
                {
                    var userDto = mapper.Map<UserDto>(user);
                    return new APIResult<UserDto>
                    {
                        Code = StatusEnumCode.Ok,
                        Message = "登录成功",
                        Data = userDto
                    };
                }
                return new APIResult<UserDto>
                {
                    Code = StatusEnumCode.Fail,
                    Message = "密码错误",
                    Data = null
                };
            }
            catch (Exception ex)
            {
                logger.LogError("登录出错", ex.Message);
                throw;
            }
        }
    }
}
